package com.maoyue.demo.controller;

import com.alibaba.excel.EasyExcel;
import com.maoyue.demo.dao.UserDAO;
import com.maoyue.demo.entity.User;
import com.maoyue.demo.listener.DemoDataListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("ymc")
@Slf4j
public class YangMinChuanController {

    @Resource
    private UserDAO userDAO;

    String PATH = "C:\\Users\\86177\\java_01\\day03\\excel-demo\\";
    
    //写进excel
    @PostMapping("/write")
    public String simpleWrite(List<User> list) {
        String fileName = PATH + "SimpleWrite.xlsx";
        EasyExcel.write(fileName, User.class).sheet("模板").doWrite(list);
        return "write ok!";
    }

    //读取excel并持久到数据库
    @GetMapping("/read")
    public String simpleRead() {
        // 有个很重要的点 DemoDataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
        String fileName = "D:\\excel\\" + "SimpleWrite.xlsx";
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        EasyExcel.read(fileName, User.class, new DemoDataListener(userDAO)).sheet().doRead();
        return "read ok!";
    }


}
